Telegram Bot API
This document provides comprehensive documentation for the Telegram Bot API endpoints and command handlers. It covers user commands (/start, /stop, /status, /stats, /web), admin commands (/users, /boo, /fu, /logs), dual-mode operation (long-polling and webhook), command routing, user session management, subscription handling, MongoDB integration, and the message formatting system. Practical examples, error handling, and troubleshooting guidance are included.
The project is organized around a modular architecture with clear separation of concerns:
CLI entry point orchestrating servers and jobs
Telegram bot server with command handlers
Webhook/FastAPI server exposing REST endpoints
Services for database, notifications, formatting, and administration
Configuration and database client modules
Diagram sources
Section sources
BotServer: Implements long-polling Telegram bot with command handlers for user and admin commands.
WebhookServer: FastAPI-based server exposing health, push subscription, notification, and stats endpoints.
DatabaseService: Wraps MongoDB operations for notices, jobs, placement offers, users, and policies.
TelegramService: Handles Telegram messaging, formatting, and broadcasting.
NotificationService: Routes notifications to configured channels and manages unsent notices.
AdminTelegramService: Provides admin-only commands with authentication via chat ID.
Configuration and DB Client: Centralized settings and MongoDB connectivity.
Section sources
The system supports two operational modes:
Long-polling Telegram bot server (BotServer) with command handlers.
Webhook/FastAPI server (WebhookServer) with REST endpoints for health, push subscriptions, notifications, and stats.
Diagram sources
Section sources
Telegram Bot Commands#
/start#
Purpose: Register user for notifications.
Request: /start
Response: Welcome message with available commands and links.
Database actions:
Insert or update user record in Users collection.
Set active subscription and timestamps.
Diagram sources
Section sources
/stop#
Purpose: Unsubscribe user from notifications.
Request: /stop
Response: Confirmation or inactive message.
Database actions:
Deactivate user subscription.
Diagram sources
Section sources
/status#
Purpose: Check subscription status.
Request: /status
Response: Active/inactive status with registration date and user ID.
Database actions:
Retrieve user by ID.
Diagram sources
Section sources
/stats#
Purpose: View placement statistics.
Request: /stats
Response: Formatted statistics including overall placement percentage, packages, and branch-wise stats.
Database actions:
Compute and return placement statistics.
Diagram sources
Section sources
/web#
Purpose: Get useful links to JIIT tools.
Request: /web
Response: HTML-formatted links.
Diagram sources
Section sources
Admin Commands#
Authentication and Permission Checks#
Admin commands are restricted to a specific chat ID configured in settings.
The AdminTelegramService validates the sender’s chat ID against the configured admin chat ID.
Only admin allowed"] Allow --> Execute["Execute admin command"] Execute --> End([Done]) Deny --> End
Diagram sources
Section sources
/users#
Purpose: List all users and subscription stats.
Request: /users
Response: User list with status and counts.
Diagram sources
Section sources
/boo #
Purpose: Broadcast message to all active users or targeted user.
Request: /boo broadcast
or /boo <chat_id> Response: Broadcast result summary.
Diagram sources
Section sources
/fu and /scrapyyy#
Purpose: Force immediate update from all sources and broadcast.
Request: /fu or /scrapyyy
Response: Progress and results summary.
Diagram sources
Section sources
/logs [lines]#
Purpose: View recent log entries.
Request: /logs [lines]
Response: Log content (HTML escaped and truncated if needed).
Diagram sources
Section sources
Dual-Mode Operation: Long-Polling and Webhook#
Long-polling mode: BotServer initializes and runs an asynchronous polling loop.
Webhook mode: WebhookServer exposes endpoints for health, push subscriptions, notifications, and stats.
Polling loop"] end subgraph "Webhook Mode" WAPI["FastAPI App
/health, /api/*"] end BPOLL --> |Telegram updates| BOT["Telegram Bot"] WAPI --> |External integrations| EXTERNAL["External Clients"]
Diagram sources
Section sources
Command Routing Mechanism#
BotServer registers command handlers for user and admin commands.
Admin commands are conditionally registered when AdminTelegramService is available.
/start, /stop, /status, /stats, /web"] RegUser --> RegAdmin["Register admin commands:
/users, /boo, /fu, /logs"] RegAdmin --> Ready["Handlers ready"]
Diagram sources
Section sources
User Session Management and Subscription Handling#
User registration and deactivation handled by DatabaseService.
Active user retrieval for broadcasting.
Diagram sources
Section sources
MongoDB Integration#
DBClient establishes and manages MongoDB connections.
DatabaseService encapsulates CRUD operations across collections: Notices, Jobs, PlacementOffers, Users, Policies, OfficialPlacementData.
Diagram sources
Section sources
Message Formatting System#
TelegramService converts Markdown to HTML/Telegram-compatible formats and handles long message splitting.
NoticeFormatterService formats notices using LLM-based extraction and structured templates.
Diagram sources
Section sources
The system exhibits strong dependency injection and separation of concerns:
BotServer depends on DatabaseService, NotificationService, TelegramService, AdminTelegramService, and PlacementStatsCalculatorService.
WebhookServer depends on DatabaseService, NotificationService, and TelegramService.
DatabaseService depends on DBClient.
Configuration is centralized via Settings with caching.
Diagram sources
Section sources
Message chunking: TelegramService splits long messages (>4000 chars) and retries without formatting if needed.
Rate limiting: Broadcast loops include small delays to avoid rate limits.
Asynchronous polling: BotServer uses asyncio for non-blocking operations.
Database indexing: Recommended indexes on frequently queried fields (e.g., notices.id, users.user_id, placement_offers.company).
Section sources
Common issues and resolutions:
Telegram bot token missing or invalid: Ensure TELEGRAM_BOT_TOKEN is set and valid.
Admin command unauthorized: Verify TELEGRAM_CHAT_ID matches the admin chat ID.
MongoDB connection failures: Check MONGO_CONNECTION_STR and network/firewall settings.
Long message delivery failures: Messages are split automatically; if formatting fails, fallback to plain text.
Webhook endpoint not reachable: Confirm server is running and port is open.
Section sources
The Telegram Bot API provides robust user and admin command handling with dual-mode operation, comprehensive MongoDB integration, and a flexible notification routing system. The documented endpoints, commands, and workflows enable reliable deployment and maintenance of placement notifications across Telegram and web push channels.
API Endpoints Summary#
GET /health: Health check
POST /api/push/subscribe: Subscribe to web push
POST /api/push/unsubscribe: Unsubscribe from web push
GET /api/push/vapid-key: Get VAPID public key
POST /api/notify: Send notification to specified channels
POST /api/notify/telegram: Send Telegram-only notification
POST /api/notify/web-push: Send Web Push-only notification
GET /api/stats: Get all statistics
GET /api/stats/placements: Get placement statistics
GET /api/stats/notices: Get notice statistics
GET /api/stats/users: Get user statistics
POST /webhook/update: Trigger update job via webhook
Section sources
Configuration Reference#
Key environment variables:
MONGO_CONNECTION_STR: MongoDB connection URI
TELEGRAM_BOT_TOKEN: Telegram bot token
TELEGRAM_CHAT_ID: Default chat/channel ID
SUPERSET_CREDENTIALS: JSON array of SuperSet credentials
GOOGLE_API_KEY: Gemini LLM API key
VAPID_PRIVATE_KEY, VAPID_PUBLIC_KEY, VAPID_EMAIL: Web push VAPID keys
WEBHOOK_PORT, WEBHOOK_HOST: Webhook server configuration
LOG_LEVEL, LOG_FILE: Logging configuration
Section sources